﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Text;
using BlogEngine.Core;
using System.Web.Routing;
using System.Web.UI.WebControls;

namespace _4mvcBlog.Core
{
    public static class UIExtension
    {
        #region RadioButtonList

        public static string RadioButtonList(this HtmlHelper html, string name, List<ListItem> items)
        {
            return RadioButtonList(html, name, items, null);
        }

        public static string RadioButtonList(this HtmlHelper html, string name, List<ListItem> items, string selectValue)
        {
            if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name", "name不能为空"); }

            if (null == items || items.Count <= 0) { return string.Empty; }
            StringBuilder sb = new StringBuilder("<span>");
            for(int i=0;i<items.Count;i++)
            {
                sb.Append(
                    string.Format("<input id=\"{0}{2}\" type=\"radio\" value=\"{1}\" name=\"{0}\" ", 
                    name, items[i].Value, i));
                if (!string.IsNullOrEmpty(selectValue) && selectValue.Equals(items[i].Value, StringComparison.OrdinalIgnoreCase))
                {
                    sb.Append(" checked=\"checked\" />");
                }
                else
                {
                    sb.Append(" />");
                }

                sb.Append(string.Format("<label for=\"{0}{2}\" >{1}</label>", name, items[i].Text, i));
            }
            sb.Append("</span>");
            return sb.ToString();
        }

        #endregion

        #region 分类列表
        /// <summary>
        /// 生成分类列表链接
        /// </summary>
        /// <param name="Html">HtmlHelper</param>
        /// <param name="Categorys">分类列表</param>
        /// <param name="container">包含该列表的最外层的容器，例如"div"</param>
        /// <param name="separator">各个分类项之间的分隔符</param>
        /// <returns></returns>
        public static string ListCategorysLink(this HtmlHelper Html, StateList<Category> Categorys, string container, string separator)
        {
            if (Categorys != null && Categorys.Count > 0)
            {
                string result = string.IsNullOrEmpty(container) ? "{0}" : "<" + container + ">{0}</" + container + ">";
                separator = separator ?? ", ";
                StringBuilder sbList = new StringBuilder();
                string link = Html.RouteCollection.GetVirtualPath
                            (Html.ViewContext.RequestContext, new RouteValueDictionary() { { "controller", "Home" }, { "action", "Category" }, {"id", ""} }).VirtualPath;
                foreach (Category c in Categorys)
                {
                    if (sbList.Length > 0)
                    {
                        sbList.Append(separator);
                    }
                    sbList.Append("<a href=\"" + link + "/" + c.Id + "\">" + c.Title + "</a>");
                }
                return string.Format(result, sbList.ToString());
            }
            return string.Empty;
        }

        /// <summary>
        /// 生成分类的复选框列表。
        /// </summary>
        /// <param name="categorys"></param>
        /// <param name="ids">被选中的分类的ID，多个ID用英文逗号分隔</param>
        /// <returns></returns>
        public static string CategorysCheckBoxList(this HtmlHelper Html, string name, List<Category> categorys, string ids)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name", "表单元素的name属性不能为空");
            }

            StringBuilder sb = new StringBuilder("<span>");
            if (categorys != null && categorys.Count > 0)
            {
                string[] arrIds = (ids ?? "").Split(',');
                string checkbox = "<input type=\"checkbox\" name=\"" + name + "\" id=\"{0}\" value=\"{1}\" {2}/><label for=\"{0}\" style=\"display:inline;\">{0}</label>&nbsp;";
                foreach (Category category in categorys)
                {
                    sb.Append(string.Format(checkbox, category.Title, category.Id, arrIds.Contains(category.Id.ToString()) ? "checked=\"checked\"" : ""));
                }
            }
            sb.Append("</span>");
            return sb.ToString();
        }
        #endregion

        #region tag列表
        /// <summary>
        /// 生成Tag列表链接
        /// </summary>
        /// <param name="Html">HtmlHelper</param>
        /// <param name="Categorys">Tag列表</param>
        /// <param name="container">包含该列表的最外层的容器，例如"div"</param>
        /// <param name="separator">各个Tag项之间的分隔符</param>
        /// <returns></returns>
        public static string ListTagsLink(this HtmlHelper Html, StateList<string> tags, string container, string separator)
        {
            if (tags != null && tags.Count > 0)
            {
                string result = string.IsNullOrEmpty(container) ? "{0}" : "<" + container + ">{0}</" + container + ">";
                separator = separator ?? ", ";
                StringBuilder sbList = new StringBuilder();
                string link = Html.RouteCollection.GetVirtualPath
                            (Html.ViewContext.RequestContext, new RouteValueDictionary() { { "controller", "Home" }, { "action", "Tag" } }).VirtualPath;
                foreach (string tag in tags)
                {
                    if (sbList.Length > 0)
                    {
                        sbList.Append(separator);
                    }
                    sbList.Append("<a href=\"" + link + "/" + tag + "\">" + tag + "</a>");
                }
                return string.Format(result, sbList.ToString());
            }
            return string.Empty;
        }
        #endregion

        #region PostLink
        /// <summary>
        /// 生成Post的链接.如果slug存在，则生成slug链接，否则生成id链接。
        /// </summary>
        public static string PostLink(this UrlHelper url, Post post)
        {
            if (!string.IsNullOrEmpty(post.Slug))
            {
                return url.Action("PostBySlug", "Home", new { slug = Utils.RemoveIllegalCharacters(post.Slug) });
            }
            else
            {
                return url.Action("Post", "Home", new { id = post.Id });
            }
        }

        #endregion

        #region 生成管理链接
        /// <summary>
        /// 生成管理链接.(编辑和删除)
        /// </summary>
        /// <param name="html"></param>
        /// <param name="manageName">操作对象(例如：Post)</param>
        /// <param name="id"></param>
        public static string ManageLink(this HtmlHelper html, string manageName, string id)
        {
            return ManageLink(html, manageName, id, null);
        }
        /// <summary>
        /// 生成管理链接.(编辑和删除)
        /// </summary>
        /// <param name="html"></param>
        /// <param name="manageName">操作对象(例如：Post)</param>
        /// <param name="id"></param>
        /// <param name="formatString">格式化字符串，例如:&lt;span&gt;|{0}&lt;/span&gt;</param>
        /// <returns></returns>
        public static string ManageLink(this HtmlHelper html, string manageName, string id, string formatString)
        {
            if (html.ViewContext.HttpContext.User.Identity.IsAuthenticated)
            {
                string format = " {0} | {1} ";
                format = string.Format(format,
                    html.ActionLink(html.Translate("Edit"), "Edit" + manageName, new { controller = "Admin", id = id }),
                    html.ActionLink(html.Translate("Delete"), "Del" + manageName, "Admin", new { id = id }, new { onclick = "return confirm('你确定要执行该操作?');" })
                    );
                if (!string.IsNullOrEmpty(formatString))
                {
                    return string.Format(formatString, format);
                }
                return format;
            }
            else
            {
                return string.Empty;
            }
        }

        #endregion

        #region 相对于Themes主题目录的路径
        /// <summary>
        /// 生成以主题目录为根路径的路径
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path">主题(Themes)目录下的路径</param>
        /// <returns></returns>
        public static string ThemeContent(this UrlHelper url, string path)
        {
            string theme = string.IsNullOrEmpty(BlogSettings.Instance.Theme) ? "Default" : BlogSettings.Instance.Theme;
            return url.Content("~/Views/Themes/" + theme + "/" + path);
        }

        #endregion

        /// <summary>
        /// 获取ViewData.ModelState中指定KEY的AttemptedValue.
        /// 如果不存在则返回string.Empty.
        /// </summary>
        /// <param name="Html"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetModelAttemptedValue(this HtmlHelper Html, string key)
        {
            ModelState state;
            if (Html.ViewData.ModelState.TryGetValue(key, out state))
            {
                return state.Value.AttemptedValue;
            }
            return string.Empty;
        }

        /// <summary>
        /// 使用资源文件将指定的文本翻译成特定区域的语言(本地化)
        /// </summary>
        public static string Translate(this HtmlHelper html, string text)
        {
            try
            {
                return html.ViewContext.Controller.ControllerContext.HttpContext.GetGlobalResourceObject("labels", text).ToString();
            }
            catch (NullReferenceException)
            {
                return text;
            }
        }
    }
}
